package com.shangcheng.server.service;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shangcheng.dubbo.api.UmsResourceApi;
import com.shangcheng.model.domain.UmsResource;
import com.shangcheng.model.vo.PageResult;
import com.shangcheng.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

/**
 * @author shiqiang
 * @version 1.0
 * @date 2022/5/13 19:01
 */
@Service
public class UmsResourceService {
    @DubboReference
    private UmsResourceApi umsResourceApi;
    /**
     * 添加后台资源
     * @param umsResource
     */
    public void createResource(UmsResource umsResource) {
        UmsResource resource= umsResourceApi.findUmsResourceByName(umsResource);
        if (!ObjectUtils.isEmpty(resource)){
            throw new BusinessException(resource.getName()+"资源已存在");
        }
        umsResourceApi.createResource(umsResource);
    }

    /**
     * 根据id删除后台资源
     * @param id
     */
    public void deleteResource(Integer id) {
        umsResourceApi.deleteResource(id);
    }

    /**
     * 分页模糊查询后台资源
     * @param params
     * @return
     */
    public PageResult resourceList(Map<String, String> params,Integer pageNum,Integer pageSize) {
        UmsResource resource= new UmsResource();
        resource.setCategoryId(Convert.toLong(params.get("categoryId")));
        resource.setName(params.get("nameKeyword"));
        resource.setUrl(params.get("urlKeyword"));
        IPage<UmsResource> page= umsResourceApi.resourceList(pageNum.toString(),pageSize.toString(),resource);
        return new PageResult(pageNum,pageSize,Convert.toInt(page.getTotal()),page.getRecords());
    }

    /**
     * 查询所有后台资源
     * @return
     */
    public List<UmsResource> allResourceList() {
        return umsResourceApi.allResourceList();
    }

    /**
     * 修改后台资源
     * @param umsResource
     */
    public void updateResource(UmsResource umsResource) {
        UmsResource resource = umsResourceApi.findUmsResourceByName(umsResource);
        if (!ObjectUtils.isEmpty(resource)){
            if (!ObjectUtils.nullSafeEquals(umsResource.getId(),resource.getId())){
                throw new BusinessException(resource.getName()+"资源已存在");
            }
        }
        umsResourceApi.updateResource(umsResource);
    }

    /**
     * 根据id获取资源详情
     * @param id
     * @return
     */
    public UmsResource findUmsResourceById(Integer id) {
        return umsResourceApi.findUmsResourceById(id);
    }
}
